#/bin/bash

SSH_PORT=22
ZK_HOME=

if [[ -f ../config/zk.cfg ]];then
  echo "加载zk配置文件"
  source ../config/zk.cfg
fi

if [[ -f ../config/config.cfg ]];then
  echo "加载config配置文件"
  source ../config/config.cfg
fi

if [[ -n "$1" ]]; then
	ZK_TAR_NAME=$1
fi

if [[ -n "$2" ]]; then
	ZK_IPS=$2
fi

if [[ -n "${workspace}" ]]; then
	ZK_HOME=${workspace}/${ZK_NAME}
else
  ZK_HOME=${ZK_NAME}
fi

path=`pwd`
zkIps=(${ZK_IPS//,/ })
IPS=`ip addr | grep 'state UP' -A2  | grep  "inet"  |awk '{print $2}' | cut -f1 -d'/'`

######## 启动服务 ########
function start(){
  if [[ ! -n "${zkIps[0]}" ]]; then
	  su ${USER} -c "${ZK_HOME}/bin/zk-stop.sh"
	  sleep 3
	  su ${USER} -c "${ZK_HOME}/bin/zk-start.sh"
  else
    ssh -p${SSH_PORT} ${zkIps[0]} "su ${USER} -c \"${ZK_HOME}/bin/zk-stop.sh\""
    sleep 3
    ssh -p${SSH_PORT} ${zkIps[0]} "su ${USER} -c \"source /etc/profile && ${ZK_HOME}/bin/zk-start.sh\""
  fi
}


######## 服务器网络校验 ########
function check(){
	
	if [[ ! -n ${ZK_NAME} ]]; then
	  echo "ZK_NAME未设置"
	  exit
	fi
	
	if [[ ! -n ${ZK_HOME} ]]; then
	  echo "ZK_HOME未设置"
	  exit
	fi
	
	if [[ ! -f ../data/${ZK_TAR_NAME} ]]; then
	  echo "未找到zookeeper安装包"
	  exit
	fi
	
  for i in ${!zkIps[@]}
  do
   if [[ ! "${IPS[@]}" =~ "${zkIps[$i]}" ]] && [[ -n ${zkIps[$i]} ]] ;then
     ssh -p${SSH_PORT} ${zkIps[$i]} "ls -la" >/dev/null
   fi
  done
}

######## 解压文件 ########
function unzip(){

	echo "正在解压zookeeper安装包。。。。"
	if [[ -d ${ZK_HOME} ]]; then
	  rm -rf ${ZK_HOME}
	fi
	mkdir -p ${ZK_HOME}/logs
  tar -zxvf ../data/${ZK_TAR_NAME} -C ${ZK_HOME} --strip-components 1 >/dev/null
  echo "完成zookeeper安装包解压。。。。"
}

######## 集群启动脚本生成 ########
function startFile(){
	if [[ ${#zkIps[*]} -ge 3 ]]; then
		  echo "ZK_IPS=${ZK_IPS}" >> ${ZK_HOME}/bin/zk-start.sh
    	echo 'zkIps=(${ZK_IPS//,/ })' >> ${ZK_HOME}/bin/zk-start.sh
    	echo 'for i in ${!zkIps[@]}' >> ${ZK_HOME}/bin/zk-start.sh
    	echo 'do' >> ${ZK_HOME}/bin/zk-start.sh
    	echo "ssh -p${SSH_PORT} ${USER}@\${zkIps[\$i]} \"${ZK_HOME}/bin/zkServer.sh start\"" >> ${ZK_HOME}/bin/zk-start.sh
    	echo 'done' >> ${ZK_HOME}/bin/zk-start.sh
    	
    	echo "ZK_IPS=${ZK_IPS}" >> ${ZK_HOME}/bin/zk-stop.sh
    	echo 'zkIps=(${ZK_IPS//,/ })' >> ${ZK_HOME}/bin/zk-stop.sh
    	echo 'for i in ${!zkIps[@]}' >> ${ZK_HOME}/bin/zk-stop.sh
    	echo 'do' >> ${ZK_HOME}/bin/zk-stop.sh
      echo "pids=\`ssh -p ${SSH_PORT} \${zkIps[\$i]} \"ps -ef | grep ${ZK_HOME} | grep -v grep | grep -v bash \" | awk '{print \$2}'\` " >> ${ZK_HOME}/bin/zk-stop.sh
      echo -e "if [[ -n \"\${pids}\" ]]; then\n for j in \${!pids[@]}\n do\n  ssh -p ${SSH_PORT} ${USER}@\${zkIps[\$i]} \"kill -9 \${pids[\$j]}\"\n done\nfi" >> ${ZK_HOME}/bin/zk-stop.sh
      echo 'done' >> ${ZK_HOME}/bin/zk-stop.sh
  else
     echo "${ZK_HOME}/bin/zkServer.sh start" >> ${ZK_HOME}/bin/zk-start.sh
  
     echo "pids=\`ps -ef | grep ${ZK_HOME} | grep -v grep | grep -v bash | awk '{print \$2}'\`" >> ${ZK_HOME}/bin/zk-stop.sh
     echo -e "if [[ -n \"\${pids}\" ]]; then\n for j in \${!pids[@]}\n do\n  kill -9 \${pids[\$j]}\n done\nfi" >> ${ZK_HOME}/bin/zk-stop.sh

  fi
  chmod +x ${ZK_HOME}/bin/zk-stop.sh
  chmod +x ${ZK_HOME}/bin/zk-start.sh
}

######## 修改配置文件 ########
function cfg(){
	echo '#!/bin/sh' > ${ZK_HOME}/conf/java.env
	
	echo "JVMFLAGS=\"-Xms${ZK_XMS} -Xmx${ZK_XMX} -XX:MetaspaceSize=${ZK_METASPACESIZE} -XX:MaxMetaspaceSize=${ZK_MAXMETASPACESIZE}\"" >> ${ZK_HOME}/conf/java.env
  cp ${ZK_HOME}/conf/zoo_sample.cfg ${ZK_HOME}/conf/zoo.cfg
  sed -i "/^tickTime=/ctickTime=${TICK_TIME}" ${ZK_HOME}/conf/zoo.cfg
  sed -i "/^initLimit=/cinitLimit=${INIT_LIMIT}" ${ZK_HOME}/conf/zoo.cfg
  sed -i "/^syncLimit=/csyncLimit=${SYNC_LIMIT}" ${ZK_HOME}/conf/zoo.cfg
  sed -i "/^dataDir=/cdataDir=${ZK_HOME}/data" ${ZK_HOME}/conf/zoo.cfg
  sed -i "/^dataLogDir=/cdataLogDir=${ZK_HOME}/logs" ${ZK_HOME}/conf/zoo.cfg
  sed -i "/^clientPort=/cclientPort=${ZK_PORT}" ${ZK_HOME}/conf/zoo.cfg
  sed -i "/^clientPortAddress=/cclientPortAddress=${CLIENT_PORT_ADDRESS}" ${ZK_HOME}/conf/zoo.cfg
  sed -i "/^maxClientCnxns=/cmaxClientCnxns=${MAX_CLIENT_CNXNS}" ${ZK_HOME}/conf/zoo.cfg
  sed -i "/^maxSessionTimeout=/cmaxSessionTimeout=${MAX_SESSION_TIME_OUT}" ${ZK_HOME}/conf/zoo.cfg
  sed -i "/^autopurge.snapRetainCount=/cautopurge.snapRetainCount=${SNAP_RETAIN_COUNT}" ${ZK_HOME}/conf/zoo.cfg
  sed -i "/^autopurge.purgeInterval=/cautopurge.purgeInterval=${PURGE_INTERVAL}" ${ZK_HOME}/conf/zoo.cfg
  if [[ ${#zkIps[*]} -ge 3 ]]; then
  	j=0
  	for i in ${!zkIps[@]}
    do
    	if [[ ! "${IPS[@]}" =~ "${zkIps[$i]}" ]] && [[ -n "${zkIps[$i]}" ]] ;then
      	SER_IP_PORT=${SER_IP_PORT}server.${i}=${zkIps[$i]}:${ZK_SER_SIGNAL_PORT}:${ZK_SER_ELECT_PORT}"\n"
      else
        j=$i
      fi
    done
    SER_IP_PORT=${SER_IP_PORT}server.${j}=${zkIps[$j]}:${ZK_SER_SIGNAL_PORT}:${ZK_SER_ELECT_PORT}"\n"
    echo -e "${SER_IP_PORT}" >> ${ZK_HOME}/conf/zoo.cfg
  fi
  sed -i '/^zookeeper.root.logger=/czookeeper.root.logger=${ZK_LOGGER}' ${ZK_HOME}/conf/log4j.properties
  sed -i '/^zookeeper.log.dir=/czookeeper.log.dir=${ZK_HOME}' ${ZK_HOME}/conf/log4j.properties
  sed -i '/^zookeeper.tracelog.dir=/czookeeper.tracelog.dir=${ZK_HOME}' ${ZK_HOME}/conf/log4j.properties
  sed -i '/^log4j.appender.ROLLINGFILE.MaxFileSize=/clog4j.appender.ROLLINGFILE.MaxFileSize=${ZK_LOG_FILE_SIZE}' ${ZK_HOME}/conf/log4j.properties
  sed -i '/^log4j.appender.ROLLINGFILE.MaxBackupIndex=/clog4j.appender.ROLLINGFILE.MaxBackupIndex=${ZK_LOG_FILE_INDEX}' ${ZK_HOME}/conf/log4j.properties
  
  echo "ZOO_LOG_DIR=${ZK_HOME}/logs" > ${ZK_HOME}/conf/zookeeper-env.sh
  echo "ZOO_LOG4J_PROP=\"${ZK_LOGGER}\"" >> ${ZK_HOME}/conf/zookeeper-env.sh
  
  sed -i '/^ZOO_LOG_FILE=/cZOO_LOG_FILE=zookeeper.log' ${ZK_HOME}/bin/zkServer.sh
  sed -i '/^_ZOO_DAEMON_OUT=/c_ZOO_DAEMON_OUT=$ZOO_LOG_DIR/zookeeper.out' ${ZK_HOME}/bin/zkServer.sh
  
}

######## 拷贝安装文件 ########
function send(){
	echo "正在拷贝zokeeper安装文件。。。"
	j=0
	for i in ${!zkIps[@]}
  do
   if [[ ! "${IPS[@]}" =~ "${zkIps[$i]}" ]] && [[ -n "${zkIps[$i]}" ]] ;then
   	 if [[ ${#zkIps[*]} -ge 3 ]]; then
   	 	  mkdir -p ${ZK_HOME}/data && echo $i > ${ZK_HOME}/data/myid
		 fi
		 ssh -p${SSH_PORT} ${zkIps[$i]} "rm -rf ${ZK_HOME} && mkdir -p ${ZK_HOME}"
     scp -P${SSH_PORT} -r ${ZK_HOME} ${zkIps[$i]}:${workspace} >> /dev/null
     ssh -p${SSH_PORT} ${zkIps[$i]} "chown -R ${USER}:${USER} ${ZK_HOME}"
   else
     j=$i
   fi
  done
  if [[ ${#zkIps[*]} -ge 3 ]]; then
  	mkdir -p ${ZK_HOME}/data && echo $j > ${ZK_HOME}/data/myid
  fi
  chown -R ${USER}:${USER} ${ZK_HOME}
  echo "完成拷贝zookeeper安装文件。。。"
}

set -e
check
unzip
cfg
startFile
send
set +e
start
